<?php


namespace app\controller\web;


use app\model\admin\login\Log;
use app\service\api\AuthServiceFacade;
use app\service\api\MemberServiceFacade;
use laytp\library\Random;
use laytp\library\Token;
use think\facade\Cache;
use think\facade\Config;

/**
 * @ApiInternal ()
 */
class Login extends Common
{
    protected $model;
    //当前模型对象
    protected $noNeedLogin = ['login', 'logout'];

    protected function _initialize()
    {
        $this->model = new \app\model\Students();
    }

    public function login()
    {

        //获取表单提交数据
        $param = $this->request->post();
        //防止密码爆破
        $fail = Cache::get('laytp-web-login-num-' . $param['username'], 1);
        if ($fail >= 5) return $this->error('失败次数过多，请三分钟后再试');

        //验证表单提交
        $validate = new \app\validate\web\students\Login();

        if (!$validate->check($param)) {
            $param['password'] = '******';
            //登录失败也不记录用户密码
            Log::create([
                'login_status'   => 2,
                'admin_id'       => 99,
                'request_body'   => json_encode($param),
                'request_header' => json_encode($this->request->header()),
                'ip'             => $this->request->ip(),
                'create_time'    => date('Y-m-d H:i:s'),
            ]);
            Cache::set('laytp-web-login-num-' . $param['username'], $fail + 1, 180);
            return $this->error($validate->getError());
        }

        //设置登录信息
        $loginUserInfo = \app\model\Students::where('phone', '=', $param['username'])
           ->field('id, phone, name, sex, type, id_card, org_id, status')->findOrEmpty();
        $loginUserInfo->login_time = date('Y-m-d H:i:s');
        $loginUserInfo->login_ip   = $this->request->ip();
        $loginUserInfo->save();
        $userId                 = $loginUserInfo['id'];
        $token                  = Random::uuid();
        $loginUserInfo['token'] = $token;
        Token::set($token, $userId, 12 * 60 * 60);

        setcookie('laytpWebToken', $token, time() + 12 * 60 * 60, '/');
        return $this->success('登录成功', [
            'user'       => $loginUserInfo,
        ]);
    }

    public function loginInfo()
    {
        $loginUserInfo = MemberServiceFacade::getUserInfo();

        return $this->success('获取成功', [
            'user'       => $loginUserInfo,
            'ltVersion'  => LT_VERSION,
        ]);
    }

    //退出登录
    public function logout()
    {
        $token = $_COOKIE['laytpWebToken'] ?: $_COOKIE['laytpWebToken'] ?: $_COOKIE['laytpWebToken'];

        Token::delete($token);
        return $this->success('退出成功');
    }
}